<template>
<!-- 设置一个类，名字叫容器，包含上传和banner两部分 -->
  <div class="container">  
    <!-- banner图部分,图片的超链接 -->
    <div class="main_banner upload_banner">
      <a href=""
        ><img class="banner_img upload_banner_img"
          src="../../public/蓝色的海.jpg"
          alt=""
      /></a>
    </div>
    <!-- 上传部分,设置了功能属性 -->
    <el-upload
      class="upload"
      ref="upload"
      accept=".jpg, .jpeg, .png"
      :auto-upload="false"
      :action="uploadUrl"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-error="handleError"
      :file-list="files"
      :data="postQiNiuData"
      :limit="10"
    >
      <el-button slot="trigger" type="primary">选取文件</el-button>
      <el-select
        v-model="tags"
        multiple
        filterable
        clearable
        placeholder="请选择上传的分类"
        style="margin-left: 20px"
      >
        <el-option
          v-for="item in tag_list"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-button style="margin-left: 50px" type="info" @click="add_tag"
        >新增分类</el-button
      >

      <el-button
        style="margin-right: 50px; float: right"
        type="success"
        @click="submitUpload"
        >上传</el-button
      >
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/jpeg/png文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import request from "../request";
export default {
  name: "upload",
  data() {
    return {
      userinfo: "",
      tag_list: [],
      tags: [],
      files: [], // 文件
      uploadToken: "", // 上传文件 token,
      postQiNiuData: {},//用于存在token与图片
      uploadUrl: "https://upload-z2.qiniup.com",//上传到七牛云的链接
    };
  },
  methods: {
    get_userinfo() {
      this.userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    },
    get_token() {
      request({
        url: "/works/get-token/",
      })
        .then((res) => {
          if (res.code == 200) {
            this.postQiNiuData.token = res.data.token;
          } else {
            this.$message.error("获取token失败");
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    handleChange(file, fileList) {
      let timestamp = new Date().valueOf(); //时间戳
      this.postQiNiuData.key = timestamp + "/" + file.name;
      this.fileList = fileList.slice(-5);
    },
    handleSuccess(response, file, fileList) {
      console.log('成功上传到七牛云，得到七牛云返回的连接')
      console.log(file)
      this.add_works(file);//将图片的链接添加到作品里面
    },

    handleError(err, file, fileList) {
      this.$message({
        message: "文件上传失败",
        type: "error",
      });
    },
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["jpg", "jpeg", "png"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是 jpg, jpeg, png格式", "error");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isLt2M) {
      //   this.$msg("上传文件大小不能超过 2MB", "error");
      //   return false;
      // }
    },
    // 上传到七牛云
    submitUpload() {
      console.log('点击了上传按钮')
      if (this.tags.length == 0) {
        this.$message.error("请先选择分类");
        return;
      }
      this.$refs.upload.submit();
    },
    get_tags() {
      if (this.userinfo) {
        request({
          url: "/works/get-tags/",
          params: {
            user_id: this.userinfo.id,
          },
        })
          .then((res) => {
            var newArr = [];
            var arrName = [];
            for (var item of res.data) {
              if (arrName.indexOf(item["name"]) == -1) {
                arrName.push(item["name"]);
                newArr.push(item);
              }
            }
            this.tag_list = newArr;
          })
          .catch((err) => {
            this.$message.error("请求失败/works/get-tags/");
          });
      } else {
        this.$message.error("请先登录");
        this.$router.push({
          name: "login",
        });
      }
    },
    add_works(file) {
      console.log('将图片链接等信息添加到数据库的作品表，与用户和分类关联')
      var params = {
        name: file.name,
        url: "http://cdn.zhirong.xyz/" + file.response.hash,
      };
      params.user_id = this.userinfo.id;
      params.tags = JSON.stringify(this.tags);
      request({
        url: "/works/add-works/",
        params: params,
        timeout: 100000,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("上传成功");
          }
        })
        .catch((err) => {
          this.$message.error("请求出错/works/add-works/");
        });
    },
    add_tag() {
      this.$prompt("请输入想要新增的分类", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          request({
            url: "/works/add-user-tag/",
            params: {
              user_id: this.userinfo.id,
              name: value,
            },
          })
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("新增成功");
                this.get_tags();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {
              this.$message.error(err);
            });
        })
        .catch(() => {});
    },
  },
  created() {
    this.get_token();
    this.get_userinfo();
    this.get_tags();
  },
  mounted() {},
};
</script>
<style>
.main_banner {
  min-height: 400px;
  text-align: center;
}

.upload_banner{
  margin: auto;

}
.upload_banner_img{
  width: 80%;
  height: 80%;
  margin: auto;
  margin-bottom: 20px;
}

 .banner_img{
   max-width: 1428px;
  
 }


.upload {
  margin: auto;
  width: 700px;
}

.text_desc {
  padding: 20px 0px 20px 0px;
  text-align: center;
  font-size: 20px;
  border-bottom: 1px solid #222;
}

.text_desc_href {
  color: #bbb;
}

.left_text {
  font-size: 15px;
  color: #bbb;
  background: #222;
  padding: 6px 10px 6px 10px;
  position: relative;
  bottom: 2px;
  font-family: "ProximaNovaT-Thin";
  border-radius: 5px;
}

.right_text {
  background: #101010;
  padding: 0;
  margin: 0;
  font-weight: 400;
  font-style: normal;
  font-family: "ProximaNovaT-Thin";
  font-size: 22px;
  color: #ccc;
}
</style>
